//
//  DateManager.swift
//  MT
//
//  Created by zhang qiang on 2018/11/21.
//  Copyright © 2018年 张强. All rights reserved.
//

import UIKit

/// 管理NSDate时间格式转换
public class DateManager: NSObject {
    
    static private var dateFormatter : DateFormatter = {
        var f = DateFormatter()
        f.locale = Locale.init(identifier: "zh_CN")
        return f
    }()
    
    static private var defaultDateFormatString = "yyyy-MM-dd HH:mm:ss"
    
    
    /// 当前时间字符串
    ///
    /// - Returns:当前时间字符串
    static public func currentTimeString() -> String{
        return self.string(date: Date.init(timeIntervalSinceNow: 0.0), format: defaultDateFormatString)
    }
    
    static public func timestamp(timeString: String, format: String) -> TimeInterval {
        dateFormatter.dateFormat = format
        let date: Date = self.dateFormatter.date(from: timeString)!
        let timestamp: TimeInterval = date.timeIntervalSince1970
        return timestamp
    }
    
    
    /// 指定时间的字符串
    ///
    /// - Parameters:
    ///   - aDate: date
    ///   - dateFormat: format if nil use default
    /// - Returns: date string
    static public func string(date aDate: Date, format dateFormat: String?) -> String{
        if let d = dateFormat {
            dateFormatter.dateFormat = d
        }else{
            dateFormatter.dateFormat = defaultDateFormatString
        }
        
        return dateFormatter.string(from: aDate)
    }
    
    
    /// 指定字符串对应的时间
    ///
    /// - Parameters:
    ///   - string: date string
    ///   - dateFormat:format if nil use default
    /// - Returns: date
    static public func date(dateString string: String, format dateFormat: String?) -> Date?{
        if let d = dateFormat {
            dateFormatter.dateFormat = d
        }else{
            dateFormatter.dateFormat = defaultDateFormatString
        }
        return dateFormatter.date(from: string)
    }
    
    /// 指定字符串对应的时间
    ///
    /// - Parameters:
    ///   - string: date string
    ///   - dateFormat:format if nil use default
    /// - Returns: date
    static public func dateString(timeInterval string: TimeInterval, format dateFormat: String?) -> String?{
        if let d = dateFormat {
            dateFormatter.dateFormat = d
        }else{
            dateFormatter.dateFormat = defaultDateFormatString
        }
        
        let date = Date(timeIntervalSince1970: string)
        return dateFormatter.string(from: date)
    }
}
